package com.liwc.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.liwc.constant.StatusCode;
import com.liwc.dao.SysCodeMapper;
import com.liwc.dto.CodeDto;
import com.liwc.message.ResponseMessage;
import com.liwc.model.SysCode;
import com.liwc.model.SysMenuTree;
import com.liwc.service.CodeService;

@Service
public class CodeServiceImpl implements CodeService {

	// log
	private static final Log log = LogFactory.getLog(CodeServiceImpl.class);

	@Autowired
	private SysCodeMapper dao;



	/**
	 * 查询所有
	 */
	@Override
	public PageInfo<SysCode> findAll(CodeDto dto) {

		// 开始分页
		PageHelper.startPage(dto.getPage(), dto.getRows());

		List<SysCode> mlist = dao.selectAll(dto);

		PageInfo<SysCode> pi = new PageInfo<SysCode>(mlist);

		return pi;
	}



	@Override
	public CodeDto findById(Integer id) {

		if(null == id){
			return new CodeDto();
		}
		
		SysCode menu = dao.selectByPrimaryKey(id);

		CodeDto dto = new CodeDto();

		try {
			BeanUtils.copyProperties(dto, menu);
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}

		return dto;
	}

	@Override
	public List<SysCode> findAllWithChild() {
		return null;
//		return dao.selectAllWithChild();
	}



	@Override
	public ResponseMessage save(SysCode entity) {
		
		CodeDto dto = new CodeDto();
		dto.setCateg(entity.getCateg());
		List<SysCode> sc = dao.selectAll(dto);
		if(!sc.isEmpty()){
			entity.setCategName(sc.get(0).getCategName());
		}else{
			log.info("保存字典数据失败！");
			return new ResponseMessage(StatusCode.FIAL, "保存失败", entity);
		}
		
		if(null != entity.getId() ){
			dao.updateByPrimaryKeySelective(entity);
		}else{
			dao.insertSelective(entity);
		}
		
		return new ResponseMessage(StatusCode.OK, "保存成功", entity);
	}



	@Override
	public List<SysMenuTree> selectTreeMenu() {
		return null;
//		return dao.selectTreeMenu();
	}



	@Override
	public ResponseMessage deleteById(Integer id) {
		dao.deleteByPrimaryKey(id);
		return new ResponseMessage(StatusCode.OK, "删除成功", id);
	}



	@Override
	public List<SysCode> getRootList() {
		return dao.selectRootList();
	}



	@Override
	public List<SysCode> getByExample(CodeDto dto) {
		
		return dao.selectAll(dto);
	}



}